import io
from typing import Any

import openpyxl

from src.core.utils.strings import is_strings_similar, remove_emojis
from src.database.models import Product


def get_excel_values(product: Product, category_name: str) -> dict[str, Any]:
    category_name = remove_emojis(category_name).strip()
    excel_values = {
        "First Name": product.first_name,
        "Surname": product.last_name,
        "Год": product.year,
        "Месяц": product.month,
        "День": product.day,
        "Номер дома": product.house_num,
        "Название улицы": product.street_name,
        "Post code": product.post_code,
        "Login": product.login,
        "Password": product.password,
        "Email": product.email,
    }
    if is_strings_similar(category_name, "bet365 uk"):
        return excel_values
    # Добавляем пароль от почты для других контор
    excel_values.update({"Email password": product.email_password})
    # Добавляем cpf и docs для bet365 br
    if is_strings_similar(category_name, "bet365 br"):
        excel_values.update(
            {
                "CPF": product.cpf,
                "Docs": product.docs,
            }
        )
    return excel_values


def export_products_to_xlsx(
    products: list[Product],
    category_name: str,
) -> bytes:
    output = io.BytesIO()
    wb = openpyxl.Workbook()
    excel_values = get_excel_values(products[0], category_name)
    try:
        ws = wb.active
        ws.append(list(excel_values.keys()))
        for product in products:
            excel_values = get_excel_values(product, category_name)
            ws.append(list(excel_values.values()))
        wb.save(output)
    finally:
        wb.close()
    output.seek(0)
    return output.read()
